#coding=utf-8
import sqlite3, time
import socket
socket.setdefaulttimeout(10)

con = sqlite3.connect('emails.sqlite3')
c = con.cursor()

c.execute('''create table if not exists rejected_emails
  (addr text,unique (addr))'''
)

def insert_emails(emails):
  c = con.cursor()
  for e in emails:
    try:
      c.execute('insert into rejected_emails values(?)', (e,) )

    except sqlite3.IntegrityError:
      
      continue
    except sqlite3.ProgrammingError, e:
      print e
      continue
  
  con.commit()
  print emails[-1]
  
import urllib
URL = 'http://email-portal.appspot.com/fetch_re'
while True:
  time.sleep(1)
  try:
    f = urllib.urlopen(URL)
    data = f.read()
  except IOError, e:
    print e
    continue
  
  else:
    if data == '0':
      print 'Fetch None!'
      break
    else:
      emails = data.split('<br/>')[:-1]
      if emails:insert_emails(emails)



